<template>
  <div class="avatar-container">
    <el-row :gutter="20">
      <!-- 左侧预览区域 -->
      <el-col :span="10">
        <el-card class="avatar-preview">
          <template #header>
            <div class="card-header">
              <span>数字人预览</span>
              <el-button type="primary" size="small" @click="handlePreviewTest">预览测试</el-button>
            </div>
          </template>
          <div class="avatar-image">
            <div class="avatar-display">
              <div class="avatar-image-container">
                <img v-if="currentAvatarImage" :src="currentAvatarImage" :alt="getProfessionText()" class="avatar-image"
                  @error="handleImageError" />
                <div v-else class="avatar-loading">
                  <el-icon class="loading-icon">
                    <Loading />
                  </el-icon>
                  <p>正在生成全身像...</p>
                  <p style="font-size: 10px; margin-top: 5px">
                    请稍候，AI正在绘制完整人物形象
                  </p>
                </div>
              </div>
            </div>
            <div class="avatar-info-container">
              <div class="avatar-info">
                <div class="avatar-profession">{{ getProfessionText() }}</div>
                <div class="avatar-description">{{ currentDescription }}</div>
              </div>
              <div class="avatar-info">
                <div class="avatar-profession">当前设置</div>
                <div class="avatar-description">
                  形象：{{ getProfessionText() }}<br>
                  性别：{{ getGenderText() }}<br>
                  表情：{{ getExpressionText() }}<br>
                  语言：{{ getLanguageText() }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧设置区域 -->
      <el-col :span="14">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基础设置 -->
          <el-tab-pane label="基础设置" name="basic">
            <el-form :model="avatarForm" label-width="120px">
              <el-form-item label="专业形象模板">
                <el-radio-group v-model="avatarForm.type" @change="handleTypeChange">
                  <el-radio-button label="engineer">
                    <el-icon>
                      <User />
                    </el-icon> 资深工程师
                  </el-radio-button>
                  <el-radio-button label="technician">
                    <el-icon>
                      <Tools />
                    </el-icon> 年轻技术员
                  </el-radio-button>
                  <el-radio-button label="architect">
                    <el-icon>
                      <House />
                    </el-icon> 建筑师
                  </el-radio-button>
                  <el-radio-button label="consultant">
                    <el-icon>
                      <Briefcase />
                    </el-icon> 专业顾问
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="性别选择">
                <el-radio-group v-model="avatarForm.gender" @change="handleGenderChange">
                  <el-radio-button label="male">男性</el-radio-button>
                  <el-radio-button label="female">女性</el-radio-button>
                  <el-radio-button label="neutral">中性</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="表情设置">
                <el-select v-model="avatarForm.expression" style="width: 100%" @change="handleExpressionChange">
                  <el-option label="正常表情" value="normal" />
                  <el-option label="专注思考" value="thinking" />
                  <el-option label="热情讲解" value="explaining" />
                  <el-option label="友善微笑" value="smiling" />
                  <el-option label="严肃认真" value="serious" />
                  <el-option label="轻松愉快" value="happy" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 语音设置 -->
          <el-tab-pane label="语音设置" name="voice">
            <el-form :model="avatarForm" label-width="120px">
              <el-form-item label="语言选择">
                <el-select v-model="avatarForm.language" style="width: 100%" @change="handleLanguageChange">
                  <el-option label="普通话" value="mandarin" />
                  <el-option label="粤语" value="cantonese" />
                  <el-option label="四川话" value="sichuan" />
                  <el-option label="东北话" value="dongbei" />
                  <el-option label="上海话" value="shanghai" />
                  <el-option label="河南话" value="henan" />
                </el-select>
              </el-form-item>

              <el-form-item label="语速调节">
                <el-slider v-model="avatarForm.voice.speed" :min="0.5" :max="2.0" :step="0.1" show-input
                  :format-tooltip="(value) => `${value}x`" @change="handleVoiceChange">
                  <template #prepend>语速</template>
                </el-slider>
              </el-form-item>

              <el-form-item label="音调调节">
                <el-slider v-model="avatarForm.voice.pitch" :min="-10" :max="10" :step="1" show-input
                  @change="handleVoiceChange">
                  <template #prepend>音调</template>
                </el-slider>
              </el-form-item>

              <el-form-item label="音量调节">
                <el-slider v-model="avatarForm.voice.volume" :min="0" :max="1" :step="0.1" show-input
                  @change="handleVoiceChange">
                  <template #prepend>音量</template>
                </el-slider>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleTestVoice">语音测试</el-button>
                <el-button @click="handleVoiceReset">重置语音</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 高级功能 -->
          <el-tab-pane label="高级功能" name="advanced">
            <el-form :model="avatarForm" label-width="120px">
              <el-form-item label="情感识别">
                <el-switch style="margin-right: 15px;" v-model="avatarForm.emotionRecognition" active-text="启用"
                  inactive-text="禁用" @change="handleEmotionChange">
                </el-switch>
                <div class="form-tip">
                  启用后，数字人能够识别用户的情感状态并做出相应回应
                </div>
              </el-form-item>

              <el-form-item label="多方言支持">
                <el-switch style="margin-right: 15px;" v-model="avatarForm.multiDialectSupport" active-text="启用"
                  inactive-text="禁用" @change="handleDialectChange">
                </el-switch>
                <div class="form-tip">启用后，支持多种方言的识别和回应</div>
              </el-form-item>

              <el-form-item label="智能回应">
                <el-select v-model="avatarForm.responseMode" style="width: 100%">
                  <el-option label="标准模式" value="standard" />
                  <el-option label="专业模式" value="professional" />
                  <el-option label="友好模式" value="friendly" />
                  <el-option label="简洁模式" value="concise" />
                </el-select>
              </el-form-item>

              <el-form-item label="年龄设置">
                <el-slider v-model="avatarForm.age" :min="20" :max="60" :step="1" show-input @change="generateAvatar">
                  <template #prepend>年龄</template>
                </el-slider>
              </el-form-item>

              <el-form-item label="自定义描述">
                <el-input v-model="customDescription" type="textarea" :rows="4"
                  placeholder="请输入自定义的数字人形象描述，例如：一位经验丰富的女性工程师，穿着蓝色工作服和安全帽，手持图纸，站在工程现场，表情专注，年龄约40岁，全身像..."
                  @blur="generateAvatar" />
                <div class="form-tip">
                  留空将使用系统自动生成的描述。建议包含：服装、道具、场景、表情、年龄等细节，确保描述为全身像
                </div>
              </el-form-item>

              <el-form-item label="个性化设置">
                <el-checkbox-group v-model="avatarForm.personality">
                  <el-checkbox label="幽默风趣">幽默风趣</el-checkbox>
                  <el-checkbox label="严谨专业">严谨专业</el-checkbox>
                  <el-checkbox label="耐心细致">耐心细致</el-checkbox>
                  <el-checkbox label="积极乐观">积极乐观</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="handleSaveSettings">保存设置</el-button>
          <el-button @click="handleResetSettings">重置设置</el-button>
          <el-button type="success" @click="handleExportSettings">导出配置</el-button>
          <el-button type="warning" @click="handleImportSettings">导入配置</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import {
  User,
  Tools,
  House,
  Briefcase,
  Loading,
} from "@element-plus/icons-vue";
import { useAppStore } from "../stores";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  generateAvatarImage,
  getAvatarTemplate,
  generateDescription,
} from "../api/avatar";

const store = useAppStore();

// 当前激活的标签页
const activeTab = ref("basic");

// AI绘图相关
const currentAvatarImage = ref("");
const isGenerating = ref(false);
const customDescription = ref("");
const currentDescription = ref("");

// 表单数据
const avatarForm = reactive({
  type: "engineer",
  gender: "male",
  expression: "normal",
  language: "mandarin",
  age: 35,
  voice: {
    speed: 1.0,
    pitch: 0,
    volume: 1.0,
  },
  emotionRecognition: true,
  multiDialectSupport: true,
  responseMode: "standard",
  personality: ["严谨专业"],
});

// 初始化表单数据
onMounted(async () => {
  const settings = store.avatarSettings;
  Object.assign(avatarForm, settings);
  await generateAvatar();
});

// 监听设置变化，自动重新生成形象
watch(
  () => [
    avatarForm.type,
    avatarForm.gender,
    avatarForm.expression,
    avatarForm.age,
  ],
  async () => {
    await generateAvatar();
  },
  { deep: true }
);

// 生成数字人形象
const generateAvatar = async () => {
  if (isGenerating.value) return;

  isGenerating.value = true;
  currentAvatarImage.value = "";

  try {
    // 生成描述
    const description =
      customDescription.value || generateDescription(avatarForm);
    currentDescription.value = description;

    // 调用AI绘图API，传递完整的设置对象
    const result = await generateAvatarImage({
      ...avatarForm,
      customDescription: customDescription.value
    });

    console.log('API返回结果:', result);

    if (result.success && result.imageUrl) {
      currentAvatarImage.value = result.imageUrl;
      ElMessage.success("数字人形象生成成功");
    } else {
      // 如果API返回失败，使用预设模板
      const template = await getAvatarTemplate(avatarForm.type, avatarForm.gender);
      currentAvatarImage.value = template.imageUrl;
      currentDescription.value = template.description;
      ElMessage.warning("使用预设模板显示");
    }
  } catch (error) {
    console.error("生成数字人形象失败:", error);
    // 如果AI生成失败，使用预设模板
    const template = await getAvatarTemplate(avatarForm.type, avatarForm.gender);
    currentAvatarImage.value = template.imageUrl;
    currentDescription.value = template.description;
    ElMessage.warning("使用预设模板显示");
  } finally {
    isGenerating.value = false;
  }
};

// 处理图片加载错误
const handleImageError = async () => {
  const template = await getAvatarTemplate(avatarForm.type, avatarForm.gender);
  currentAvatarImage.value = template.imageUrl;
};

// 获取数字人CSS类
const getAvatarClass = () => {
  return `avatar-${avatarForm.type}-${avatarForm.gender}`;
};

// 获取表情CSS类
const getExpressionClass = () => {
  return `expression-${avatarForm.expression}`;
};

// 获取专业文本
const getProfessionText = () => {
  const professions = {
    engineer: "资深工程师",
    technician: "年轻技术员",
    architect: "建筑师",
    consultant: "专业顾问",
  };
  return professions[avatarForm.type] || "未知";
};

// 获取性别文本
const getGenderText = () => {
  const genders = {
    male: "男性",
    female: "女性",
    neutral: "中性",
  };
  return genders[avatarForm.gender] || "未知";
};

// 获取表情文本
const getExpressionText = () => {
  const expressions = {
    normal: "正常表情",
    thinking: "专注思考",
    explaining: "热情讲解",
    smiling: "友善微笑",
    serious: "严肃认真",
    happy: "轻松愉快",
  };
  return expressions[avatarForm.expression] || "未知";
};

// 获取语言文本
const getLanguageText = () => {
  const languages = {
    mandarin: "普通话",
    cantonese: "粤语",
    sichuan: "四川话",
    dongbei: "东北话",
    shanghai: "上海话",
    henan: "河南话",
  };
  return languages[avatarForm.language] || "未知";
};

// 处理类型变化
const handleTypeChange = () => {
  ElMessage.success(`已切换到${getProfessionText()}形象`);
};

// 处理性别变化
const handleGenderChange = () => {
  ElMessage.success(`已切换到${getGenderText()}形象`);
};

// 处理表情变化
const handleExpressionChange = () => {
  ElMessage.success(`表情已切换为${getExpressionText()}`);
};

// 处理语言变化
const handleLanguageChange = () => {
  ElMessage.success(`语言已切换为${getLanguageText()}`);
};

// 处理语音变化
const handleVoiceChange = () => {
  // 语音参数变化时的处理
};

// 处理情感识别变化
const handleEmotionChange = (value) => {
  ElMessage.success(value ? "已启用情感识别" : "已禁用情感识别");
};

// 处理方言支持变化
const handleDialectChange = (value) => {
  ElMessage.success(value ? "已启用多方言支持" : "已禁用多方言支持");
};

// 预览测试
const handlePreviewTest = () => {
  generateAvatar();
};

// 语音测试
const handleTestVoice = () => {
  ElMessage.success("正在播放测试语音...");
  // 这里可以添加实际的语音测试逻辑
};

// 重置语音
const handleVoiceReset = () => {
  avatarForm.voice = {
    speed: 1.0,
    pitch: 0,
    volume: 1.0,
  };
  ElMessage.success("语音设置已重置");
};

// 保存设置
const handleSaveSettings = () => {
  store.updateAvatarSettings(avatarForm);
  ElMessage.success("数字人设置保存成功");
};

// 重置设置
const handleResetSettings = () => {
  ElMessageBox.confirm("确定要重置所有数字人设置吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    Object.assign(avatarForm, {
      type: "engineer",
      gender: "male",
      expression: "normal",
      language: "mandarin",
      voice: { speed: 1.0, pitch: 0, volume: 1.0 },
      emotionRecognition: true,
      multiDialectSupport: true,
      responseMode: "standard",
      personality: ["严谨专业"],
    });
    ElMessage.success("设置已重置");
  });
};

// 导出配置
const handleExportSettings = () => {
  const config = JSON.stringify(avatarForm, null, 2);
  const blob = new Blob([config], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "avatar-settings.json";
  a.click();
  URL.revokeObjectURL(url);
  ElMessage.success("配置已导出");
};

// 导入配置
const handleImportSettings = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".json";
  input.onchange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const config = JSON.parse(e.target.result);
          Object.assign(avatarForm, config);
          ElMessage.success("配置导入成功");
        } catch (error) {
          ElMessage.error("配置文件格式错误");
        }
      };
      reader.readAsText(file);
    }
  };
  input.click();
};
</script>

<style scoped>
.avatar-container {
  background-color: #f5f7fa;
}

.avatar-preview,
.avatar-settings {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 400px;
}

.avatar-display {
  width: 400px;
  /* height: 450px; */
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px auto;
  /* box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); */
  /* padding: 20px; */
}

.avatar-info-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  gap: 20px;
  margin-top: 20px;
}

.avatar-image-container {
  /* width: 200px; */
  /* height: 320px; */
  border-radius: 15px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  /* box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); */
  /* margin: 0 auto 15px auto; */
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 15px;
}

.avatar-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-align: center;
}

.loading-icon {
  font-size: 24px;
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* AI绘图相关样式 */
.avatar-image-container:hover {
  transform: scale(1.05);
  transition: transform 0.3s ease;
}

.avatar-body {
  margin-top: 10px;
  text-align: center;
}



.avatar-info {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 180px;
  flex: 1;
  height: 140px;
  display: flex;
  flex-direction: column;
}

.avatar-info p {
  /* margin: 5px 0; */
  font-size: 12px;
}

.avatar-profession {
  font-size: 14px;
  color: #333;
  background: #f0f2f5;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 12px;
  text-align: center;
  font-weight: 500;
  flex-shrink: 0;
}

.avatar-description {
  font-size: 12px;
  color: #666;
  background: #f8f9fa;
  padding: 10px;
  border-radius: 6px;
  text-align: left;
  line-height: 1.4;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 10px;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 5px;
}

:deep(.el-slider__prepend) {
  min-width: 60px;
}
</style>